Conditions | 54 |
Total Lines | 388 |
Code Lines | 206 |
Lines | 112 |
Ratio | 28.87 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like angular-sanitize.js ➔ $SanitizeProvider often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | /** |
||
157 | function $SanitizeProvider() { |
||
158 | var svgEnabled = false; |
||
159 | |||
160 | this.$get = ['$$sanitizeUri', function($$sanitizeUri) { |
||
161 | if (svgEnabled) { |
||
162 | extend(validElements, svgElements); |
||
163 | } |
||
164 | return function(html) { |
||
165 | var buf = []; |
||
166 | htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { |
||
167 | return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); |
||
168 | })); |
||
169 | return buf.join(''); |
||
170 | }; |
||
171 | }]; |
||
172 | |||
173 | |||
174 | /** |
||
175 | * @ngdoc method |
||
176 | * @name $sanitizeProvider#enableSvg |
||
177 | * @kind function |
||
178 | * |
||
179 | * @description |
||
180 | * Enables a subset of svg to be supported by the sanitizer. |
||
181 | * |
||
182 | * <div class="alert alert-warning"> |
||
183 | * <p>By enabling this setting without taking other precautions, you might expose your |
||
184 | * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned |
||
185 | * outside of the containing element and be rendered over other elements on the page (e.g. a login |
||
186 | * link). Such behavior can then result in phishing incidents.</p> |
||
187 | * |
||
188 | * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg |
||
189 | * tags within the sanitized content:</p> |
||
190 | * |
||
191 | * <br> |
||
192 | * |
||
193 | * <pre><code> |
||
194 | * .rootOfTheIncludedContent svg { |
||
195 | * overflow: hidden !important; |
||
196 | * } |
||
197 | * </code></pre> |
||
198 | * </div> |
||
199 | * |
||
200 | * @param {boolean=} flag Enable or disable SVG support in the sanitizer. |
||
201 | * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called |
||
202 | * without an argument or self for chaining otherwise. |
||
203 | */ |
||
204 | this.enableSvg = function(enableSvg) { |
||
205 | if (isDefined(enableSvg)) { |
||
206 | svgEnabled = enableSvg; |
||
207 | return this; |
||
208 | } else { |
||
|
|||
209 | return svgEnabled; |
||
210 | } |
||
211 | }; |
||
212 | |||
213 | ////////////////////////////////////////////////////////////////////////////////////////////////// |
||
214 | // Private stuff |
||
215 | ////////////////////////////////////////////////////////////////////////////////////////////////// |
||
216 | |||
217 | bind = angular.bind; |
||
218 | extend = angular.extend; |
||
219 | forEach = angular.forEach; |
||
220 | isDefined = angular.isDefined; |
||
221 | lowercase = angular.lowercase; |
||
222 | noop = angular.noop; |
||
223 | |||
224 | htmlParser = htmlParserImpl; |
||
225 | htmlSanitizeWriter = htmlSanitizeWriterImpl; |
||
226 | |||
227 | nodeContains = window.Node.prototype.contains || /** @this */ function(arg) { |
||
228 | // eslint-disable-next-line no-bitwise |
||
229 | return !!(this.compareDocumentPosition(arg) & 16); |
||
230 | }; |
||
231 | |||
232 | // Regular Expressions for parsing tags and attributes |
||
233 | var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, |
||
234 | // Match everything outside of normal chars and " (quote character) |
||
235 | NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g; |
||
236 | |||
237 | |||
238 | // Good source of info about elements and attributes |
||
239 | // http://dev.w3.org/html5/spec/Overview.html#semantics |
||
240 | // http://simon.html5.org/html-elements |
||
241 | |||
242 | // Safe Void Elements - HTML5 |
||
243 | // http://dev.w3.org/html5/spec/Overview.html#void-elements |
||
244 | var voidElements = toMap('area,br,col,hr,img,wbr'); |
||
245 | |||
246 | // Elements that you can, intentionally, leave open (and which close themselves) |
||
247 | // http://dev.w3.org/html5/spec/Overview.html#optional-tags |
||
248 | var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), |
||
249 | optionalEndTagInlineElements = toMap('rp,rt'), |
||
250 | optionalEndTagElements = extend({}, |
||
251 | optionalEndTagInlineElements, |
||
252 | optionalEndTagBlockElements); |
||
253 | |||
254 | // Safe Block Elements - HTML5 |
||
255 | var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + |
||
256 | 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + |
||
257 | 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); |
||
258 | |||
259 | // Inline Elements - HTML5 |
||
260 | var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + |
||
261 | 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + |
||
262 | 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); |
||
263 | |||
264 | // SVG Elements |
||
265 | // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements |
||
266 | // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. |
||
267 | // They can potentially allow for arbitrary javascript to be executed. See #11290 |
||
268 | var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + |
||
269 | 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + |
||
270 | 'radialGradient,rect,stop,svg,switch,text,title,tspan'); |
||
271 | |||
272 | // Blocked Elements (will be stripped) |
||
273 | var blockedElements = toMap('script,style'); |
||
274 | |||
275 | var validElements = extend({}, |
||
276 | voidElements, |
||
277 | blockElements, |
||
278 | inlineElements, |
||
279 | optionalEndTagElements); |
||
280 | |||
281 | //Attributes that have href and hence need to be sanitized |
||
282 | var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href'); |
||
283 | |||
284 | var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + |
||
285 | 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + |
||
286 | 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + |
||
287 | 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + |
||
288 | 'valign,value,vspace,width'); |
||
289 | |||
290 | // SVG attributes (without "id" and "name" attributes) |
||
291 | // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes |
||
292 | var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + |
||
293 | 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + |
||
294 | 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + |
||
295 | 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + |
||
296 | 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + |
||
297 | 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + |
||
298 | 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + |
||
299 | 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + |
||
300 | 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + |
||
301 | 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + |
||
302 | 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + |
||
303 | 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + |
||
304 | 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + |
||
305 | 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + |
||
306 | 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); |
||
307 | |||
308 | var validAttrs = extend({}, |
||
309 | uriAttrs, |
||
310 | svgAttrs, |
||
311 | htmlAttrs); |
||
312 | |||
313 | function toMap(str, lowercaseKeys) { |
||
314 | var obj = {}, items = str.split(','), i; |
||
315 | for (i = 0; i < items.length; i++) { |
||
316 | obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; |
||
317 | } |
||
318 | return obj; |
||
319 | } |
||
320 | |||
321 | var inertBodyElement; |
||
322 | (function(window) { |
||
323 | var doc; |
||
324 | if (window.document && window.document.implementation) { |
||
325 | doc = window.document.implementation.createHTMLDocument('inert'); |
||
326 | } else { |
||
327 | throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document'); |
||
328 | } |
||
329 | var docElement = doc.documentElement || doc.getDocumentElement(); |
||
330 | var bodyElements = docElement.getElementsByTagName('body'); |
||
331 | |||
332 | // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one |
||
333 | if (bodyElements.length === 1) { |
||
334 | inertBodyElement = bodyElements[0]; |
||
335 | } else { |
||
336 | var html = doc.createElement('html'); |
||
337 | inertBodyElement = doc.createElement('body'); |
||
338 | html.appendChild(inertBodyElement); |
||
339 | doc.appendChild(html); |
||
340 | } |
||
341 | })(window); |
||
342 | |||
343 | /** |
||
344 | * @example |
||
345 | * htmlParser(htmlString, { |
||
346 | * start: function(tag, attrs) {}, |
||
347 | * end: function(tag) {}, |
||
348 | * chars: function(text) {}, |
||
349 | * comment: function(text) {} |
||
350 | * }); |
||
351 | * |
||
352 | * @param {string} html string |
||
353 | * @param {object} handler |
||
354 | */ |
||
355 | function htmlParserImpl(html, handler) { |
||
356 | if (html === null || html === undefined) { |
||
357 | html = ''; |
||
358 | } else if (typeof html !== 'string') { |
||
359 | html = '' + html; |
||
360 | } |
||
361 | inertBodyElement.innerHTML = html; |
||
362 | |||
363 | //mXSS protection |
||
364 | var mXSSAttempts = 5; |
||
365 | do { |
||
366 | if (mXSSAttempts === 0) { |
||
367 | throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable'); |
||
368 | } |
||
369 | mXSSAttempts--; |
||
370 | |||
371 | // strip custom-namespaced attributes on IE<=11 |
||
372 | if (window.document.documentMode) { |
||
373 | stripCustomNsAttrs(inertBodyElement); |
||
374 | } |
||
375 | html = inertBodyElement.innerHTML; //trigger mXSS |
||
376 | inertBodyElement.innerHTML = html; |
||
377 | } while (html !== inertBodyElement.innerHTML); |
||
378 | |||
379 | var node = inertBodyElement.firstChild; |
||
380 | View Code Duplication | while (node) { |
|
381 | switch (node.nodeType) { |
||
382 | case 1: // ELEMENT_NODE |
||
383 | handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); |
||
384 | break; |
||
385 | case 3: // TEXT NODE |
||
386 | handler.chars(node.textContent); |
||
387 | break; |
||
388 | } |
||
389 | |||
390 | var nextNode; |
||
391 | if (!(nextNode = node.firstChild)) { |
||
392 | if (node.nodeType === 1) { |
||
393 | handler.end(node.nodeName.toLowerCase()); |
||
394 | } |
||
395 | nextNode = getNonDescendant('nextSibling', node); |
||
396 | if (!nextNode) { |
||
397 | while (nextNode == null) { |
||
398 | node = getNonDescendant('parentNode', node); |
||
399 | if (node === inertBodyElement) break; |
||
400 | nextNode = getNonDescendant('nextSibling', node); |
||
401 | if (node.nodeType === 1) { |
||
402 | handler.end(node.nodeName.toLowerCase()); |
||
403 | } |
||
404 | } |
||
405 | } |
||
406 | } |
||
407 | node = nextNode; |
||
408 | } |
||
409 | |||
410 | while ((node = inertBodyElement.firstChild)) { |
||
411 | inertBodyElement.removeChild(node); |
||
412 | } |
||
413 | } |
||
414 | |||
415 | function attrToMap(attrs) { |
||
416 | var map = {}; |
||
417 | for (var i = 0, ii = attrs.length; i < ii; i++) { |
||
418 | var attr = attrs[i]; |
||
419 | map[attr.name] = attr.value; |
||
420 | } |
||
421 | return map; |
||
422 | } |
||
423 | |||
424 | |||
425 | /** |
||
426 | * Escapes all potentially dangerous characters, so that the |
||
427 | * resulting string can be safely inserted into attribute or |
||
428 | * element text. |
||
429 | * @param value |
||
430 | * @returns {string} escaped text |
||
431 | */ |
||
432 | View Code Duplication | function encodeEntities(value) { |
|
433 | return value. |
||
434 | replace(/&/g, '&'). |
||
435 | replace(SURROGATE_PAIR_REGEXP, function(value) { |
||
436 | var hi = value.charCodeAt(0); |
||
437 | var low = value.charCodeAt(1); |
||
438 | return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; |
||
439 | }). |
||
440 | replace(NON_ALPHANUMERIC_REGEXP, function(value) { |
||
441 | return '&#' + value.charCodeAt(0) + ';'; |
||
442 | }). |
||
443 | replace(/</g, '<'). |
||
444 | replace(/>/g, '>'); |
||
445 | } |
||
446 | |||
447 | /** |
||
448 | * create an HTML/XML writer which writes to buffer |
||
449 | * @param {Array} buf use buf.join('') to get out sanitized html string |
||
450 | * @returns {object} in the form of { |
||
451 | * start: function(tag, attrs) {}, |
||
452 | * end: function(tag) {}, |
||
453 | * chars: function(text) {}, |
||
454 | * comment: function(text) {} |
||
455 | * } |
||
456 | */ |
||
457 | View Code Duplication | function htmlSanitizeWriterImpl(buf, uriValidator) { |
|
458 | var ignoreCurrentElement = false; |
||
459 | var out = bind(buf, buf.push); |
||
460 | return { |
||
461 | start: function(tag, attrs) { |
||
462 | tag = lowercase(tag); |
||
463 | if (!ignoreCurrentElement && blockedElements[tag]) { |
||
464 | ignoreCurrentElement = tag; |
||
465 | } |
||
466 | if (!ignoreCurrentElement && validElements[tag] === true) { |
||
467 | out('<'); |
||
468 | out(tag); |
||
469 | forEach(attrs, function(value, key) { |
||
470 | var lkey = lowercase(key); |
||
471 | var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); |
||
472 | if (validAttrs[lkey] === true && |
||
473 | (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { |
||
474 | out(' '); |
||
475 | out(key); |
||
476 | out('="'); |
||
477 | out(encodeEntities(value)); |
||
478 | out('"'); |
||
479 | } |
||
480 | }); |
||
481 | out('>'); |
||
482 | } |
||
483 | }, |
||
484 | end: function(tag) { |
||
485 | tag = lowercase(tag); |
||
486 | if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { |
||
487 | out('</'); |
||
488 | out(tag); |
||
489 | out('>'); |
||
490 | } |
||
491 | // eslint-disable-next-line eqeqeq |
||
492 | if (tag == ignoreCurrentElement) { |
||
493 | ignoreCurrentElement = false; |
||
494 | } |
||
495 | }, |
||
496 | chars: function(chars) { |
||
497 | if (!ignoreCurrentElement) { |
||
498 | out(encodeEntities(chars)); |
||
499 | } |
||
500 | } |
||
501 | }; |
||
502 | } |
||
503 | |||
504 | |||
505 | /** |
||
506 | * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare |
||
507 | * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want |
||
508 | * to allow any of these custom attributes. This method strips them all. |
||
509 | * |
||
510 | * @param node Root element to process |
||
511 | */ |
||
512 | View Code Duplication | function stripCustomNsAttrs(node) { |
|
513 | while (node) { |
||
514 | if (node.nodeType === window.Node.ELEMENT_NODE) { |
||
515 | var attrs = node.attributes; |
||
516 | for (var i = 0, l = attrs.length; i < l; i++) { |
||
517 | var attrNode = attrs[i]; |
||
518 | var attrName = attrNode.name.toLowerCase(); |
||
519 | if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { |
||
520 | node.removeAttributeNode(attrNode); |
||
521 | i--; |
||
522 | l--; |
||
523 | } |
||
524 | } |
||
525 | } |
||
526 | |||
527 | var nextNode = node.firstChild; |
||
528 | if (nextNode) { |
||
529 | stripCustomNsAttrs(nextNode); |
||
530 | } |
||
531 | |||
532 | node = getNonDescendant('nextSibling', node); |
||
533 | } |
||
534 | } |
||
535 | |||
536 | function getNonDescendant(propName, node) { |
||
537 | // An element is clobbered if its `propName` property points to one of its descendants |
||
538 | var nextNode = node[propName]; |
||
539 | if (nextNode && nodeContains.call(node, nextNode)) { |
||
540 | throw $sanitizeMinErr('elclob', 'Failed to sanitize html because the element is clobbered: {0}', node.outerHTML || node.outerText); |
||
541 | } |
||
542 | return nextNode; |
||
543 | } |
||
544 | } |
||
545 | |||
757 |